package demo.practice.leetcode_eveyday;

import java.util.*;


class KV {
    private Integer k;
    private TreeSet<Integer> set;

    public KV(Integer k,TreeSet<Integer> set){
        this.k=k;
        this.set=set;
    }

    public Integer getK() {
        return k;
    }

    public void setK(Integer k) {
        this.k = k;
    }

    public TreeSet<Integer> getSet() {
        return set;
    }

    public void setSet(TreeSet<Integer> set) {
        this.set = set;
    }
}

public class P697 {
    public static void main(String[] args) {
        P697 p697 = new P697();
        p697.findShortestSubArray(new int[]{1,2,2,3,1});
    }

    public int findShortestSubArray(int[] nums) {
        if(nums==null || nums.length==0)
            return 0;
        PriorityQueue<KV> queue = new PriorityQueue<>((i, j) -> {
           if(i.getSet().size() == j.getSet().size()){
               return (i.getSet().last()- i.getSet().first())-(j.getSet().last()- j.getSet().first());
           }else
               return  j.getSet().size()-i.getSet().size();
        });
        Map<Integer, TreeSet<Integer>> times = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (times.get(nums[i]) == null) {
                TreeSet<Integer> s = new TreeSet<>();
                s.add(i);
                times.put(nums[i], s);

            }else{
                times.get(nums[i]).add(i);
            }
        }
//        Set<Map.Entry<Integer, Set<Integer>>> entries = times.entrySet();

        for (Map.Entry<Integer, TreeSet<Integer>> e :times.entrySet()){
            queue.add(new KV(e.getKey(),e.getValue()));
        }

        TreeSet<Integer> set = queue.poll().getSet();
        return set.last()-set.first()+1;
    }
}
